/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-08-24 16:19:02
 * @LastEditTime : 2023-08-27 08:42:12
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Pages\Front\Assets\Modal\AIBox.jsx
 * @Description  :
 */
import './AIBox.scss'
import { Button, Input, message } from 'antd'
import { useState } from 'react'
import { CopyOutlined, NotificationOutlined } from '@ant-design/icons'
import { project } from '../../../../Common/Data'
import { CommonFiles } from '../../../../Common/Configure/CommonParameter'

// CommonFiles
import { useRequest, useLatest } from 'ahooks'
import { Http } from '../../../../Common/Api'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import dayjs from 'dayjs'
import { ModalBox } from '../../../../Common/Modal/ModalBox'
const { imageUrl } = project[window.location.hostname]
const { Search } = Input
const { speechSynthesis } = window

export const AIBox001 = () => {
    const [messageApi, contextHolder] = message.useMessage()
    const [loading, setLoading] = useState(false)
    const [InputText, setInputText] = useState('')

    const [history, setHistory] = useState([])
    const HistoryLatest = useLatest(history)

    const { runAsync } = useRequest(Http, { manual: true })

    const onSearch = () => {
        setLoading(true)
        const question = {
            uuid: new Date().getTime(),
            type: 'question',
            time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            text: InputText,
        }
        HistoryLatest.current.push(question)
        setHistory(HistoryLatest.current)
        getResponse()
        setInputText('')
    }

    const getResponse = () => {
        runAsync({ url: 'posAIInteraction', data: { question: InputText } }).then(res => {
            const response = {
                uuid: new Date().getTime(),
                type: 'response',
                time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                text: res.response,
                source: res.source_documents,
            }
            // speak
            HistoryLatest.current.push(response)
            setHistory(HistoryLatest.current)
            setLoading(false)
        })
    }

    const [SpeakStatus, setSpeakStatus] = useState(false)

    const copy = text => {
        console.log(text)
    }

    const speak = text => {
        const msg = new SpeechSynthesisUtterance(text)
        msg.lang = 'zh-cn'
        if (!SpeakStatus) {
            speechSynthesis.speak(msg)
            setSpeakStatus(true)
        } else {
            speechSynthesis.cancel()
            setSpeakStatus(false)
        }
    }

    const [OptionsCall, setOptionsCall] = useState()

    return (
        <div className="AIBox001">
            {contextHolder}
            <div className="top">
                <div className="left">
                    {history.map(({ uuid, type, time, text, source }) => (
                        <div key={uuid} className={type}>
                            <div>
                                <div>{time}</div>
                                <div>{text}</div>
                                {type !== 'question' && (
                                    <div>
                                        <div className="Title">出处参考</div>
                                        {source.map((item, index) => (
                                            <div key={index}>{item}</div>
                                        ))}
                                        <div className="Title">参考文献</div>
                                        <div className="link">
                                            {source.map((item, index) => {
                                                const regex = /《([^》]*)》/
                                                const match = item.match(regex)
                                                const result = match && match[1]
                                                if (result) {
                                                    return (
                                                        <Button
                                                            key={index}
                                                            type="link"
                                                            onClick={() => {
                                                                setOptionsCall({
                                                                    type: 'Annex',
                                                                    data: {
                                                                        url: CommonFiles + result + '.pdf',
                                                                        title: result,
                                                                        width: '90vw',
                                                                    },
                                                                })
                                                            }}
                                                        >
                                                            [{index + 1}] {result}
                                                        </Button>
                                                    )
                                                } else return false
                                            })}
                                        </div>
                                    </div>
                                )}
                                {type !== 'question' && (
                                    <div className="options">
                                        <CopyToClipboard
                                            text={text}
                                            onCopy={() => messageApi.success('内容已添加至剪切板!')}
                                        >
                                            <Button shape="circle" icon={<CopyOutlined />} onClick={() => copy(text)} />
                                        </CopyToClipboard>
                                        <Button
                                            shape="circle"
                                            icon={<NotificationOutlined />}
                                            onClick={() => speak(text)}
                                        />
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
                <div className="right">
                    <img src={imageUrl + 'intelligence.gif'} alt="" />
                </div>
            </div>
            <div className="btm">
                <div className="left">
                    <Search
                        placeholder="请输入"
                        value={InputText}
                        enterButton="互动"
                        size="large"
                        loading={loading}
                        onChange={e => setInputText(e.target.value)}
                        onSearch={onSearch}
                    />
                </div>
                <div className="right">
                    {/* disabled */}
                    {/* <Button type="primary" block size="large" onClick={speak}>
                        语音
                    </Button> */}
                </div>
            </div>
            <ModalBox OptionsCall={OptionsCall} />
        </div>
    )
}
